@echo off
REM 设置日期变量
set DATE=%date:~0,4%%date:~5,2%%date:~8,2%
REM 设置MySQL用户名和密码
set USER=root
set PASSWORD=你的密码
REM 设置备份保存路径
set BACKUP_PATH=E:\mysql_backup
REM 设置mysqldump路径
set MYSQLDUMP_PATH="C:\Program Files\MySQL\MySQL Server 8.0\bin\mysqldump.exe"
REM 设置日志路径
set LOG_PATH=%BACKUP_PATH%\logs

REM 记录备份开始时间
for /f "tokens=1-4 delims=:. " %%a in ("%time%") do set STARTTIME=%%a%%b%%c

REM 创建备份目录（如果不存在）
if not exist %BACKUP_PATH% (
    mkdir %BACKUP_PATH%
)
if not exist %LOG_PATH% (
    mkdir %LOG_PATH%
)

REM 备份所有数据库
set BACKUP_FILE=%BACKUP_PATH%\all_databases_%DATE%.sql
%MYSQLDUMP_PATH% -u%USER% -p%PASSWORD% --all-databases > %BACKUP_FILE%
set RET=%ERRORLEVEL%

REM 记录备份结束时间
for /f "tokens=1-4 delims=:. " %%a in ("%time%") do set ENDTIME=%%a%%b%%c

REM 计算耗时（秒）
set /a STARTSEC=%STARTTIME:~0,2%*3600 + %STARTTIME:~2,2%*60 + %STARTTIME:~4,2%
set /a ENDSEC=%ENDTIME:~0,2%*3600 + %ENDTIME:~2,2%*60 + %ENDTIME:~4,2%
set /a DURATION=%ENDSEC%-%STARTSEC%
if %DURATION% lss 0 set /a DURATION=%DURATION%+86400

if %RET%==0 (
    echo 备份成功！
    echo 日期: %DATE%  备份文件: %BACKUP_FILE%  开始: %STARTTIME%  结束: %ENDTIME%  耗时: %DURATION%秒  状态: 成功 >> %LOG_PATH%\backup_%DATE%.log
) else (
    echo 备份失败！
    echo 日期: %DATE%  备份文件: %BACKUP_FILE%  开始: %STARTTIME%  结束: %ENDTIME%  耗时: %DURATION%秒  状态: 失败  错误码: %RET% >> %LOG_PATH%\backup_%DATE%.log
)

REM 删除7天前的备份和日志
forfiles /p %BACKUP_PATH% /m *.sql /d -7 /c "cmd /c del @path"
forfiles /p %LOG_PATH% /m *.log /d -7 /c "cmd /c del @path"
